package development;

import iplayparticle.view.iplayparticleResources;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameControl;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TouchScreenListener;
import state.component.BottomBar;
import state.component.Checkbox;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.md5.MD5;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.array.StringArray;
import development.bean.User;
import development.listener.ConnectionDoneListener;
import development.socket.SocketClientUtil;

public class FrmLogin extends GameForm implements EventListener, TouchScreenListener {
  private final String HOT_LINE = "0963421990";
  private final String COPY_RIGHT = "Copy Right TS";
  
  private final int NUMBER_OF_ITEM = 5;
  
  private GameImage buttonImage;
  private ImageText text8;
  private int chooseIndex;

  private TextField userNameTextField;
  private TextField passwordTextField;
  private Checkbox rememberPasswordCheckbox;
  private Sprite loginButtonSprite;
  private Sprite registerButtonSprite;
  
  private BottomBar bottomBar;
  
  private static GameForm singleton;
  
  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmLogin();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    userNameTextField = new TextField(_manager, TextField.CONSTRAINT_ANY, Constants.TEXT_FIELD_STYLE);
    passwordTextField = new TextField(_manager, TextField.CONSTRAINT_PASSWORD, Constants.TEXT_FIELD_STYLE);
    rememberPasswordCheckbox = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE, 0, 0).setLabel("Nhớ mật khẩu");
    
    if (GameConstants.IS_240x320_SCREEN) {
      userNameTextField.setPosition(47, 83);
      userNameTextField.setSize(150, 20);
      passwordTextField.setPosition(47, 127);
      passwordTextField.setSize(150, 20);
      rememberPasswordCheckbox.setPosition(43, 157);
      loginButtonSprite = new Sprite(buttonImage, _manager, 47, 190, Constants.TOP_LEFT_ANCHOR);
      registerButtonSprite = new Sprite(buttonImage, _manager, 197, 190, Constants.TOP_RIGHT_ANCHOR);
    } else {
      userNameTextField.setPosition(87, 73);
      userNameTextField.setSize(150, 20);
      passwordTextField.setPosition(87, 117);
      passwordTextField.setSize(150, 20);
      rememberPasswordCheckbox.setPosition(83, 147);
      loginButtonSprite = new Sprite(buttonImage, _manager, 87, 180, Constants.TOP_LEFT_ANCHOR);
      registerButtonSprite = new Sprite(buttonImage, _manager, 237, 180, Constants.TOP_RIGHT_ANCHOR);
    }
    
    if (Global.loginInfo.isSaveUserNameAndPassword() || Global.loginInfo.isAutoLogin()) {
      Global.currentUser = new User(Global.loginInfo.getUserName());
      Global.currentUser.setPasswordMd5(MD5.toBase64(GameStringUtils.toByteArrayUTF8(Global.loginInfo.getPassword())));
      userNameTextField.setText(Global.currentUser.getName());
      passwordTextField.setText(Global.loginInfo.getPassword());
      rememberPasswordCheckbox.setChecked(Global.loginInfo.isSaveUserNameAndPassword());
      chooseIndex = 3;
    } else {
      chooseIndex = 0;
    }
    
    loginButtonSprite.setTouchScreenListener(this);
    loginButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (chooseIndex == 3) {
          text8.drawString2(g, "Đăng nhập", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        } else {
          text8.drawString2(g, "Đăng nhập", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        }
      }
    });
    
    registerButtonSprite.setTouchScreenListener(this);
    registerButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (chooseIndex == 4) {
          text8.drawString2(g, "Đăng ký", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        } else {
          text8.drawString2(g, "Đăng ký", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        }
      }
    });
    
    GameMenu menu = new GameMenu(null, new String[] { "Đăng ký TK", "Quên mật khẩu", "Giới thiệu", "Hotline hỗ trợ", "Xóa dữ liệu", "Thoát" }, 6, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    bottomBar = DrawUtils.getBottomBar(_manager);
    bottomBar.setLabels("Menu", "Đăng nhập", "Xóa");
    bottomBar.setLeftMenu("Menu", menu);
    updateFocus();
    
    // Hiển thị xem user có muốn tạo tài khoản không
    if (Global.loginInfo == null || !Global.loginInfo.isHasData()) {
      new GameControl() {
        public void perform() {
          if ((Global.systemCanvas.frmCurrent == FrmLogin.instance()) 
              && (Global.loginInfo == null || !Global.loginInfo.isHasData()) 
              && userNameTextField.getText().equals("")) {
            Global.alert.showAlert1(FrmLogin.this, GameAlert.YES_NO_TYPE, StringArray.create2("Chào mừng bạn đến với", " hệ thống WinPlay. Bạn có muốn", " tạo tài khoản mới?"), 95);
          }
        }
      }.setTimeInterval(15000).start();
    }
  }
  
  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);
    text8.drawString2(g, "Version " + Constants.VERSION, GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 5, 5, GameConstants.TOP_RIGHT_ANCHOR);

    if (GameConstants.IS_240x320_SCREEN) {
      drawFor240x320(g);
    } else {
      drawFor320x240(g);
    }
  }

  private void drawFor240x320(Graphics g) {
    text8.drawString2(g, "Tên tài khoản", GameColor.WHITE_CODE, 47, 63, GameConstants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, "Mật khẩu", GameColor.WHITE_CODE, 47, 108, GameConstants.TOP_LEFT_ANCHOR);
    
    text8.drawString2(g, COPY_RIGHT, GameColor.YELLOW_CODE, 5, 5, GameConstants.TOP_LEFT_ANCHOR);
//    text8.drawString(g, "Hotline: " + HOT_LINE, Color.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 5, GameConstants.SCREEN_HEIGHT - 32, GameConstants.BOTTOM_RIGHT_ANCHOR);
  }

  private void drawFor320x240(Graphics g) {
    text8.drawString2(g, "Tên tài khoản", GameColor.WHITE_CODE, 87, 53, GameConstants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, "Mật khẩu", GameColor.WHITE_CODE, 87, 98, GameConstants.TOP_LEFT_ANCHOR);
    
    text8.drawString2(g, COPY_RIGHT, GameColor.YELLOW_CODE, 5, 5, GameConstants.TOP_LEFT_ANCHOR);
//    text8.drawString(g, "Hotline: " + HOT_LINE, Color.YELLOW_CODE, 5, 20, GameConstants.TOP_LEFT_ANCHOR);
  }
  
  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.ENTER:
      if (chooseIndex == 0) {
        userNameTextField.pointerReleased(userNameTextField, userNameTextField.getRealX(), userNameTextField.getRealY());
      } else if (chooseIndex == 1) {
        passwordTextField.pointerReleased(passwordTextField, passwordTextField.getRealX(), passwordTextField.getRealY());
      } else if (chooseIndex == 2) {
        rememberPasswordCheckbox.setChecked(!rememberPasswordCheckbox.isChecked());
      } else if (chooseIndex == 3) {
        if ((Global.authenClient == null) || !Global.authenClient.isConnectSuccess) {
          GameGlobal.alert.showAlert(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang đăng nhập...").setAlertTimeOut(SocketClientUtil.TIME_OUT);
          ConnectionDoneListener.needAuthenAfterConnect = true;
          return;
        }
        login();
      } else if (chooseIndex == 4) {
        GameGlobal.nextState(FrmRegister.instance(), null);
      }
      break;
    case Key.UP:
      if (chooseIndex > 0) {
        chooseIndex--;
        updateFocus();
      }
      break;
    case Key.LEFT:
      if (chooseIndex == 4) {
        chooseIndex = 3;
        updateFocus();
      }
      break;
    case Key.RIGHT:
      if (chooseIndex == 3) {
        chooseIndex = 4;
        updateFocus();
      }
      break;
    case Key.DOWN:
      if (chooseIndex < NUMBER_OF_ITEM - 1) {
        chooseIndex++;
        updateFocus();
      }
      break;
    case Key.SOFT_RIGHT:
    case Key.BACKSPACE:
      if (chooseIndex == 0) {
        userNameTextField.deleteLastChar();
      } else if (chooseIndex == 1) {
        passwordTextField.deleteLastChar();
      }
      break;
    default:
      if (chooseIndex == 0) {
        userNameTextField.keyReleased(null, keyCode);
      } else if (chooseIndex == 1) {
        passwordTextField.keyReleased(null, keyCode);
      }
      break;
    }
  }
  
  public void login() {
    if ((userNameTextField.getText().length() == 0) || (passwordTextField.getText().length() == 0)) {
      Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1("Hãy nhập tài khoản", "và mật khẩu"));
      return;
    }
    // kiem tra xem co phai ban cua tinhvan ko
    if(Global.provider.getId() != Constants.TINHVAN_PROVIDER_ID){
      Global.loginInfo.setUserName(userNameTextField.getText());
    } else{
      Global.loginInfo.setUserName(userNameTextField.getText().toUpperCase());
    }
    Global.loginInfo.setPassword(passwordTextField.getText());
    Global.loginInfo.setAutoLogin(false);
    Global.loginInfo.setSaveUserNameAndPassword(rememberPasswordCheckbox.isChecked());
    SocketClientUtil.login(true);
  }

  public void updateFocus() {
    userNameTextField.setFocused(false);
    passwordTextField.setFocused(false);
    rememberPasswordCheckbox.setFocused(false);
    switch (chooseIndex) {
    case 0:
      userNameTextField.setFocused(true);
      bottomBar.setCenterLabel("Chọn");
      break;
    case 1:
      passwordTextField.setFocused(true);
      bottomBar.setCenterLabel("Chọn");
      break;
    case 2:
      rememberPasswordCheckbox.setFocused(true);
      bottomBar.setCenterLabel("Chọn");
      break;
    case 3:
      bottomBar.setCenterLabel("Đăng nhập");
      break;
    case 4:
      bottomBar.setCenterLabel("Đăng ký");
      break;
    }
  }
  
  public void onActionPerform(Event event) {
    // "Đăng ký TK", "Quên mật khẩu", "Giới thiệu", "Hotline hỗ trợ", "Thoát"
    String action = event.getAction();
    if (action.equals("Đăng ký TK")) {
      GameGlobal.nextState(FrmRegister.instance(), null);
    } else if (action.equals("Quên mật khẩu")) {
    	GameGlobal.nextState(FrmResetPassword.instance(), null);
    } else if (action.equals("Giới thiệu")) {
      Hashtable data = new Hashtable();
      data.put("helpId", "iplay");
      data.put("title", "Hướng dẫn chơi Iplay");
      GameGlobal.nextState(FrmGuide.instance(), data);
    } else if (action.equals("Hotline hỗ trợ")) {
      Global.getMidlet().platformRequest("tel:" + HOT_LINE);
    } else if (action.equals("Xóa dữ liệu")) {
      Rms.clearAllRms();
      userNameTextField.setText("");
      passwordTextField.setText("");
      rememberPasswordCheckbox.setChecked(false);
    } else if (action.equals("Thoát")) { // Thoát
      GameGlobal.alert.showAlert2(this, GameAlert.YES_NO_TYPE, "Bạn có muốn thoát?", 99);
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if ((alertId == 99) && (eventType == GameAlert.YES_BUTTON)) { // Thoát
      GameGlobal.getMidlet().notifyDestroyed();
    } else if ((alertId == 95) && (eventType == GameAlert.YES_BUTTON)) { // Hỏi người dùng có muốn tạo tài khoản không
      Global.nextState(FrmRegister.instance(), null);
    }
  }

  public void destroy() {
    userNameTextField = null;
    passwordTextField = null;
    rememberPasswordCheckbox = null;
    text8 = null;
    buttonImage = null;
    bottomBar = null;
    loginButtonSprite = null;
    registerButtonSprite = null;
  }

  public void pointerDragged(Sprite source, int x, int y) {
  }

  public void pointerPressed(Sprite source, int x, int y) {
  }

  public void pointerReleased(Sprite source, int x, int y) {
    if (loginButtonSprite == source) {
      chooseIndex = 3;
      updateFocus();
      keyReleased(Key.FIRE);
    } else if (registerButtonSprite == source) {
      chooseIndex = 4;
      updateFocus();
      keyReleased(Key.FIRE);
    }
  }
}
